package com.jprocms.module.cms.util;

import cn.hutool.core.util.NumberUtil;
import com.jpro.framework.security.core.LoginUser;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.web.IPageUrl;
import freemarker.core.Environment;
import freemarker.ext.servlet.HttpRequestParametersHashModel;
import freemarker.template.AdapterTemplateModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;

public class FrontContextUtil {
    /**
     * 模板资源表达式
     */
    public static final String R_EXP = "${r}";
    /**
     * 部署路径
     */
    public static final String BASE = "base";
    /**
     * 站点
     */
    public static final String SITE = "site";
    /**
     * 用户
     */
    public static final String USER = "user";
    /**
     * 页码
     */
    public static final String PAGE_NO = "pageNo";
    /**
     * 总条数
     */
    public static final String COUNT = "count";
    /**
     * 起始条数
     */
    public static final String FIRST = "first";

    /**
     * 页面翻页地址
     */
    public static final String HREF = "href";
    /**
     * href前半部（相对于分页）
     */
    public static final String HREF_FORMER = "hrefFormer";
    /**
     * href后半部（相对于分页）
     */
    public static final String HREF_LATTER = "hrefLatter";
    /**
     * 页面完整地址
     */
    public static final String LOCATION = "location";

    public static final int DEF_COUNT = 50;

    public static final String PARAMS = "Params";

    public static final String DEF = "def";
    public static final String CONFIG = "config";
    public static final String DEFAULT_SITE = "defaultSite";
    public static final String RESOURCE = "resource";
    public static final String DYNAMIC = "dynamic";
    public static final String PAGE = "page";
    public static final String PAGE_SIZE = "pageSize";
    public static final String URL = "url";

    public static final String FRONT_API_PREFIX = "api";
    public static final String QUERY_STRING = "queryString";
    public static final String PAGE_URL_RESOLVER = "pageUrlResolver";

    public static void setUser(HttpServletRequest request, @Nullable LoginUser user) {
        request.setAttribute(USER, user);
    }

    public static void setData(HttpServletRequest request) {
        SiteDO site = CmsContextUtil.getSite();
        if (site == null) {
            throw new IllegalStateException("Context site not found. request URI: " + request.getRequestURI());
        }
        request.setAttribute(PARAMS, new HttpRequestParametersHashModel(request));
        request.setAttribute(CONFIG, site.getGlobalConfigDO());
        request.setAttribute(SITE, site);
        request.setAttribute(BASE, site.getBase());
        request.setAttribute(FRONT_API_PREFIX, site.getFrontApi());
        request.setAttribute(RESOURCE, CmsContextUtil.isPc() ? site.getResPath() : site.getH5ResPath());
        request.setAttribute(DYNAMIC, true);
        String pageParam = request.getParameter(PAGE);
        int page = 1;
        if (NumberUtil.isNumber(pageParam)) {
            page = CommonParamValidUtil.validPage(Integer.valueOf(pageParam));
        }
        request.setAttribute(PAGE, page);
        request.setAttribute(URL, request.getRequestURL());
        request.setAttribute(QUERY_STRING, request.getQueryString());
    }

    public static void setDate(Map<String, Object> dataModel, SiteDO site, String url, int page,
                               @Nullable IPageUrl iPageUrl) {
        dataModel.put(PARAMS, Collections.EMPTY_MAP);
        dataModel.put(CONFIG, site.getGlobalConfigDO());
        dataModel.put(BASE, site.getBase());
        dataModel.put(SITE, site);
        dataModel.put(FRONT_API_PREFIX, site.getFrontApi());
        dataModel.put(RESOURCE, site.getResPath());
        dataModel.put(DYNAMIC, false);
        dataModel.put(PAGE, page);
        dataModel.put(URL, url);
        dataModel.put(QUERY_STRING, null);
        dataModel.put(PAGE_URL_RESOLVER, iPageUrl);
    }

    public static SiteDO getSite(Environment env) throws TemplateModelException {
        TemplateModel model = env.getDataModel().get(SITE);
        if (model instanceof AdapterTemplateModel) {
            return (SiteDO) ((AdapterTemplateModel) model).getAdaptedObject(SiteDO.class);
        } else {
            throw new TemplateModelException("'" + SITE + "' not found in DataModel");
        }
    }

    public static Long getSiteId(Environment env) throws TemplateModelException {
        return getSite(env).getId();
    }

    private FrontContextUtil() {
    }

}
